// 持久化缓存token的函数
import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'
// 引入login api
import { login, getUserInfo, getUserDetail } from '@/api/user'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  userInfo: {}
}

const mutations = {
  setToken(state, token) {
    // vuex && cookie 同步设置token
    state.token = token
    setToken(token)
  },

  removeToken(state) {
    // vuex && cookie 同步移除token
    state.token = null
    removeToken()
  },

  setUserInfo(state, res) {
    state.userInfo = res
  },

  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  async login({ commit }, data) {
    const token = await login(data)
    // console.log(data)
    commit('setToken', token)
    setTimeStamp()
  },

  async getUserInfo({ commit }) {
    const res = await getUserInfo()
    const detail = await getUserDetail(res.userId)
    commit('setUserInfo', { ...res, ...detail })
    return res // 权限管理的伏笔
  },

  logout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
    commit('permission/setRoutes', [], { root: true })
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

